<?php

declare(strict_types=1);

namespace app\yperp\common;

use CURLFile;
use Exception;

class ImageMatting
{
    static $URL = 'http://localhost:7000/api/remove';

    static function extract($filePath = '', $model = 'u2net', bool $a = false, $af = 240, $ab = '10', $ae = 10, bool $om = false, bool $ppm = false)
    {
 
        // 校验路径是否安全，防止目录遍历攻击
        if (!preg_match('/\.(jpg|jpeg|png|gif)$/i', $filePath)) {
            throw new Exception("Unsupported file format.");
        }

        // 校验路径是否安全，防止目录遍历攻击
        if (!file_exists($filePath)) {
            throw new Exception("file not exists");
        }
        //获取文件的MME类型
        $mime = mime_content_type($filePath);
        $file =   new CURLFile($filePath, $mime);
        $models = ["isnet-anime", "isnet-general-use", "sam", "silueta", "u2net_cloth_seg", "u2net_custom", "u2net_human_seg", "u2net", "u2netp"];
        $fields = array(
            'file' => $file,
            'model' => in_array($model, $models) ? $model : 'u2net',
            'a' => $a ? 'true' : 'false',
            'af' => ($af >= 0 && $af <= 255) ? $af : '10',
            'ab' => ($ab >= 0 && $ab <= 255) ? $ab : '10',
            'ae' => ($ae < 0) ? 0 : $ae,
            'om' => $om ? 'true' : 'false',
            'ppm' => $ppm ? 'true' : 'false',
        );
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, self::$URL);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 设置请求头
        $headers = array(
            'accept: application/json',
            'Content-Type: multipart/form-data'
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 指定POST数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

        // 执行并获取HTML文档内容
        $output = curl_exec($ch);

        // 关闭CURL会话
        curl_close($ch);

        return $output;
    }
}
